package cn.itcast.bos.delivery.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.pdf.PdfExportUtil;
import cn.afterturn.easypoi.pdf.entity.PdfExportParams;
import cn.itcast.bos.base.action.BaseAction;
import cn.itcast.bos.delivery.service.WayBillService;
import cn.itcast.bos.domain.delivery.WayBill;


@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private String wayBillIds ;

	public void setWayBillIds(String wayBillIds) {
		this.wayBillIds = wayBillIds;
	}

	@Autowired
	private WayBillService wayBillService;
	@Action(value="save_waybill",results={@Result(name="success",type="json"),@Result(name="input",type="json")})
	public String save(){
			if(t.getOrder()==null||t.getOrder().getId()==null||t.getOrder().getId()==0){
				t.setOrder(null);
			}
		try {
			wayBillService.save(t);
			logger.info(toString());
			ServletActionContext.getContext().getValueStack().push(1);
			return SUCCESS;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ServletActionContext.getContext().getValueStack().push(0);
			return INPUT;
		}
		
	}
	
	
	@Action(value="show_waybill",results={@Result(name="success",type="json")})
	public String show(){
		Pageable pageable=new PageRequest(page-1, rows);
		if(StringUtils.isBlank(t.getWayBillNum())&&StringUtils
				.isBlank(t.getSendAddress())&&StringUtils
				.isBlank(t.getRecAddress())&&StringUtils
				.isBlank(t.getSendProNum())&&(t.getSignStatus()==null||t.getSignStatus()==0)){
			Page<WayBill> page=wayBillService.show(pageable);
			putIntoValueStack(page);
		}else{
			Page<WayBill> page = wayBillService.searchFromElastic(pageable,t);
			putIntoValueStack(page);
		}
		return SUCCESS;
	}
	
	@Action(value="exportEcel")
	public String exportEcel() throws IOException{
		 Iterable<WayBill>  waybills= wayBillService.searchFromElastic(t);
		 List<WayBill> list=new ArrayList<WayBill>();
		 for (WayBill wayBill : waybills) {
			list.add(wayBill);
		}
		 logger.info(list.get(0).toString());
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null,"sheetA",ExcelType.XSSF),
				WayBill.class,list);
		ServletActionContext.getResponse().setContentType("application/vnd.ms-excel");
		String filename=new String("运单信息.xlsx".getBytes(),"ISO-8859-1");
		ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+filename);
		workbook.write(ServletActionContext.getResponse().getOutputStream());
		workbook.close();
		return NONE;
	}
	
	@Action(value="exportPdf")
	public String exportPdf() throws IOException, Exception{
		 Iterable<WayBill>  waybills= wayBillService.searchFromElastic(t);
		 List<WayBill> list=new ArrayList<WayBill>();
		 for (WayBill wayBill : waybills) {
			list.add(wayBill);
		}
		ServletActionContext.getResponse().setContentType("application/pdf");
		String filename=new String("运单信息.pdf".getBytes(),"ISO-8859-1");
		ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+filename);
		
		/*模板技术*/
		String jrxml=ServletActionContext.getServletContext().getRealPath("/WEB-INF/iReport/waybill.jrxml");
		JasperReport report = JasperCompileManager.compileReport(jrxml);
		JasperPrint fillReport = JasperFillManager.fillReport(report,null,new JRBeanCollectionDataSource(list));
		JRPdfExporter exporter=new JRPdfExporter();
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, fillReport);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,ServletActionContext.getResponse().getOutputStream());
		exporter.exportReport();
//		easypoi
//		 PdfExportParams params=new PdfExportParams("运单数据");
//		 PdfExportUtil.exportPdf(params, WayBill.class, list,
//				 ServletActionContext.getResponse().getOutputStream());
		 return NONE;
	}
	@Action(value="getwayBillByNum",results={@Result(name="success",type="json",params={"excludeNullProperties","true"})})
	public String getwayBillByNum(){
		logger.info(t.getWayBillNum());
		WayBill wayBill=wayBillService.findByWayBillNum(t.getWayBillNum());
		logger.info("满足条件的运单为：{}",wayBill);
		ServletActionContext.getContext().getValueStack().push(wayBill);
		return SUCCESS;
	}
	
	@Action(value="transit",results={@Result(name="success",type="json")})
	public String trasnit(){
		Map<String,Object> map=new HashMap<String ,Object>();
		try {
			logger.info("运输配送信息");
			logger.info(wayBillIds);
			String [] str=wayBillIds.split(",");
			List<Integer> list=new ArrayList<Integer>();
			for (int i = 0; i < str.length; i++) {
				list.add(Integer.parseInt(str[i]));
			}
			wayBillService.transit(list);
			map.put("success", true);
			map.put("msg", "运输配送成功");
		} catch (Exception e) {
			map.put("success", false);
			map.put("msg", "运输配送失败");
			e.printStackTrace();
		}
		ServletActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
}
